<?php
/**
 * Pusher 工具类
 *
 * @link https://dashboard.pusher.com/ - 请使用 panx google 账号登录，查看后台
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/10/11 10:08
 * @copyright PanxSoft Inc.
 */

namespace App\Services\Pusher;

use Pusher\Pusher;

/**
 * Class PanxPusher
 *
 * @package App\Services\Pusher
 *
 * @mixin Pusher
 */
class PanxPusher
{
    /**
     * @var Pusher
     */
    protected $pusher;

    /**
     * PanxPusher constructor.
     * @throws \Pusher\PusherException
     */
    public function __construct()
    {
        $this->pusher = $this->init();
    }

    /**
     * @return Pusher
     * @throws \Pusher\PusherException
     */
    public static function init(): Pusher
    {
        $pusher_conf = config('broadcasting.connections.pusher');

        $options = [
            'cluster' => $pusher_conf['options']['cluster'],
            'useTLS' => $pusher_conf['options']['encrypted']
        ];

        $pusher = new Pusher(
            $pusher_conf['key'], $pusher_conf['secret'], $pusher_conf['app_id'],
            $options
        );

        return $pusher;
    }

    /**
     * @param string $channel
     * @param string $event
     * @param array $data
     *
     * @return array|bool
     * @throws \Pusher\PusherException
     */
    public function sendData(string $channel, string $event, array $data)
    {
        return $this->trigger((array) $channel, $event, $data);
    }

    /**
     * @param string $channel
     * @param string $event
     * @param string $message
     *
     * @return array|bool
     * @throws \Pusher\PusherException
     */
    public function sendMessage(string $channel, string $event, string $message)
    {
        $data['message'] = $message;

        return $this->sendData($channel, $event, $data);
    }

    /**
     * @param array $channels
     * @param string $event
     * @param array $data
     *
     * @return array|bool
     * @throws \Pusher\PusherException
     */
    public function trigger(array $channels, string $event, array $data)
    {
        return $this->pusher->trigger($channels, $event, $data);
    }

    /**
     * @deprecated - 测试 pusher 用
     *
     * @example
     *  打开 http://mirror.me/test/pusher/index.html
     *  或 打开链接 https://dashboard.pusher.com/apps/619337/getting_started
     *  运行此方法，登录 panx 的 google 账号，可以直接在网页上收到 alert 信息
     *
     * @param string $msg
     *
     * @return array|bool - 如返回 true 是成功
     * @throws \Pusher\PusherException
     */
    public static function sendMessageDemo($msg = 'hello mirror')
    {
        $pusher = new self();

        return $pusher->sendMessage('my-channel', 'my-event', $msg);
    }

    /**
     * @param $method
     * @param $arguments
     *
     * @return mixed
     */
    public function __call($method, $arguments)
    {
        if (! method_exists($this, $method)) {
            return $this->pusher->$method(...$arguments);
        }
    }
}